<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i>后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item><a href="/permission/admin">管理员管理</a></el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <div style="margin: 0 0 20px 0;">
      <el-button type="primary" size="medium"
                 @click="$router.push('/permission/admin/add-new')">
        添加管理员
      </el-button>
    </div>

    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" align="center"></el-table-column>
      <el-table-column prop="username" label="名称" width="180" align="center"
                       show-overflow-tooltip></el-table-column>
      <el-table-column prop="gender" label="性别" align="center" width="100px"
                       show-overflow-tooltip></el-table-column>
      <el-table-column label="头像" align="center" width="100px">
        <template slot-scope="scope">
          <el-avatar :size="30" :src="scope.row.avatar"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="phoneNumber" label="电话" align="center" width="180px"
                       show-overflow-tooltip></el-table-column>
      <el-table-column prop="description" label="简介" align="center"
                       show-overflow-tooltip></el-table-column>
      <el-table-column prop="enable" label="是否启用" width="180" align="center"
                       show-overflow-tooltip>
        <template slot-scope="scope">
          <el-switch
              @change="toggleEnable(scope.row)"
              v-model="scope.row.enable"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#999">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="查看" width="100" align="center">
        <template slot-scope="scope">
        <el-button size="small" @click="openStandard(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit" circle
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" circle
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="text-align: right; margin: 10px auto;">
      <el-pagination
          @current-change="changePage"
          layout="total, prev, pager, next"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize">
      </el-pagination>
    </div>

    <el-dialog :visible.sync="standardFormVisible"  title="管理员详情">
      <el-descriptions :model="editForm" column="1" border size="medium">
        <el-descriptions-item label="用户名" prop="username">{{editForm.username}}</el-descriptions-item>
        <el-descriptions-item label="密码" prop="password">{{editForm.password}}</el-descriptions-item>
        <el-descriptions-item label="头像" prop="avatar"><el-image
            style="width: 100px; height: 100px"
            :src="editForm.avatar"
            :fit="fit"></el-image></el-descriptions-item>
        <el-descriptions-item label="性别" prop="gender">{{editForm.gender}}</el-descriptions-item>
        <el-descriptions-item label="电话" prop="phoneNumber">{{editForm.phoneNumber}}</el-descriptions-item>
        <el-descriptions-item label="年龄" prop="age">{{editForm.age}}</el-descriptions-item>
        <el-descriptions-item label="身份证" prop="idCard">{{editForm.idCard}}</el-descriptions-item>
        <el-descriptions-item label="地址" prop="address">{{editForm.address}}</el-descriptions-item>
        <el-descriptions-item label="简介" prop="description">{{editForm.description}}</el-descriptions-item>
        <el-descriptions-item label="角色" prop="roleNames"><el-tag size="small" v-for="item in editForm.roleNames">{{ item }}</el-tag></el-descriptions-item>
      </el-descriptions>
    </el-dialog>



    <el-dialog title="编辑管理员" :visible.sync="dialogFormVisible">
      <el-form :model="editForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <div style="width: 40%;">
        <el-form-item label="名称" prop="username">
          <el-input v-model="editForm.username" autocomplete="off"></el-input>
        </el-form-item>
        </div>
        <div style="width: 40%;">
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" autocomplete="off" type="password"></el-input>
        </el-form-item>
        </div>
        <div style="width: 40%;">
        <el-form-item label="性别" prop="gender">
          <el-radio v-model="editForm.gender" label="男">男</el-radio>
          <el-radio v-model="editForm.gender" label="女">女</el-radio>
        </el-form-item>
        </div>
        <el-form-item label="头像" prop="avatar">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:9202/resources/upload/image/product"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <div style="width: 40%;">
        <el-form-item label="电话" prop="phoneNumber">
          <el-input v-model="editForm.phoneNumber" autocomplete="off"></el-input>
        </el-form-item>
        </div>
        <div style="width: 50%;">
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="editForm.idCard" autocomplete="off"></el-input>
        </el-form-item>
        </div>
        <div style="width: 60%;">
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" autocomplete="off"></el-input>
        </el-form-item>
        </div>
        <div style="width: 28%;">
        <el-form-item label="年龄" prop="age">
          <el-input v-model="editForm.age" autocomplete="off"></el-input>
        </el-form-item>
        </div>
        <div style="width: 60%;">
        <el-form-item label="简介" prop="description">
          <el-input v-model="editForm.description" autocomplete="off"></el-input>
        </el-form-item>
        </div>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="editForm.roleIds" multiple placeholder="请选择">
            <el-option
                v-for="item in roleListOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleListOptions: [],
      tableData: [],
      total: 0,
      pageSize: 0,
      currentPage: 1,
      dialogFormVisible: false,
      standardFormVisible:false,
      editForm: {
        id:'',
        username: '',
        password:'',
        gender:'',
        avatar:'',
        idCard:'',
        address:'',
        phoneNumber:'',
        age:'',
        description: '',
        enable:'',
        roleNames:[],
        roleIds:[],
      },
      rules: {
        username: [
          {required: true, message: '请输入名称', trigger: 'blur'},
          {min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur'}
        ],
        age: [
          {required: true, message: '请输入年龄', trigger: 'blur'},
          {pattern: /^(1[8-9]|[2-5]\d|99)$/,message: '请输入正确年龄',trigger: 'blur'}
        ],
        nickname: [
          {required: true, message: '请输入名称', trigger: 'blur'},
          {min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur'}
        ],
        avatar: [
          {required: true, message: '请选择头像', trigger: 'blur'}
        ],
        phoneNumber: [
          {required: true, message: '请输入手机号码', trigger: 'blur'},
          {len: 11,message: '电话号码格式错误',trigger: 'blur'}
        ],
        idCard: [
          {required: true, message: '请输入身份证号', trigger: 'blur'},
          {pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            message: '身份证格式错误',trigger: 'blur'}
        ],
        description: [
          {required: true, message: '请输入简介', trigger: 'blur'},
        ],
        address: [
          {required: true, message: '请输入地址', trigger: 'blur'},
        ],
        enable: [],
        roleIds: [
          {required: true, message: '请选择角色', trigger: 'blur'},
        ]
      }
    }
  },
  methods: {
    // 上传成功后的回调
    handleAvatarSuccess(res, file) {
      this.editForm.avatar = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M
    },
    openStandard(admin){
      this.loadRoleList();
      let url = 'http://localhost:9201/admin/standard?id=' + admin.id;
      this.axios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.editForm = jsonResult.data;
          this.standardFormVisible = true;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAdminList();
            }
          });
        }
      })
    },
    loadRoleList() {
      let url = 'http://localhost:9201/role/list?query=all';
      console.log('url = ' + url);


      this.axios.get(url).then((response) => {
        let jsonResult = response.data;
        console.log(jsonResult);
        if (jsonResult.state == 20000) {
          this.roleListOptions = jsonResult.data.list;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    openEditDialog(admin) {
      this.loadRoleList();
      let url = 'http://localhost:9201/admin/standard?id=' + admin.id;


      this.axios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.editForm = jsonResult.data;
          this.dialogFormVisible = true;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAdminList();
            }
          });
        }
      });
    },
    toggleEnable(admin) {
      let enableText = ['禁用', '启用'];
      let url = 'http://localhost:9201/admin/' + admin.id;

      if (admin.id == 1) {
        this.$alert('不能禁用系统管理员！', '错误', {
          confirmButtonText: '确定',
          callback: action => {
            this.loadAdminList();
          }
        });
        return;
      }

      let enable = admin.enable;
      if (enable == 1) {
        url += '/enable';
      } else {
        url += '/disable';
      }
      console.log('url = ' + url);

      this.axios.post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '将【' + admin.username + '】的启用状态修改为【' + enableText[enable] + '】成功！',
            type: 'success'
          });
          this.loadAdminList();
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAdminList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(err => {
        let message = '服务器响应错误！';
        this.$alert(message, '操作失败', {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
      });
    },
    submitEditForm(){
      let url = 'http://localhost:9201/admin/update';
      console.log('url = ' + url);

      if (this.editForm.id == 1) {
        if (this.editForm.roleIds.indexOf(1) == -1) {
          this.$alert('管理员必须是系统管理员', '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          return;
        }
      }

      let formData = this.qs.stringify(this.editForm);

      console.log("formData=" + formData)
      let localJwt = localStorage.getItem('localJwt');


      this.axios.post(url,formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state==20000){
          this.$message({
            message: '修改管理员成功',
            type: 'success'
          });
          this.dialogFormVisible = false;
          this.loadAdminList();
        } else if (jsonResult.state == 40400){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadAdminList();
            }
          });
        }else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },
    openDeleteConfirm(admin) {
      if (admin.id == 1) {
        this.$alert('不能删除系统管理员！', '错误', {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        return;
      }

      this.$confirm('此操作将永久删除【' + admin.id + '-' + admin.username + '】管理员，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(admin);
      }).catch(() => {
      });
    },
    handleDelete(admin) {
      let url = 'http://localhost:9201/admin/delete';

      let formData = 'id=' + admin.id;

      this.axios.post(url, formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '删除管理员成功！',
            type: 'success'
          });
          this.loadAdminList();
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAdminList();
            }
          });
        } else if (jsonResult.state == 40900) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    changePage(value) {
      this.$router.replace('?page=' + value);
      this.loadAdminList();

    },
    loadAdminList() {
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }

      let url = 'http://localhost:9201/admin/list?page=' + page;


      this.axios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
          console.log(this.tableData.avatar,'头像');
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    }
  },
  mounted() {
    this.loadAdminList();
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.picture-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  line-height: 78px;
  text-align: center;
}
.avatar {
  width: 78px;
  height: 78px;
  display: block;
}
</style>